<?php

namespace App\Jobs\Finance;

use App\Jobs\Finance\Traits\CommonBillTrait;
use App\Jobs\Finance\Traits\CommonBranchBillTrait;
use App\Jobs\Finance\Traits\CreateBillTrait;
use App\Jobs\Finance\Traits\FinanceBranchBillTrait;
use App\Models\CustomerManager;
use App\Models\Finance\FinanceCustomerBill;
use App\Models\SubAccount\SubAccount;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Database\Query\Builder;

class FinanceBillJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels,FinanceBranchBillTrait, CreateBillTrait, CommonBranchBillTrait, CommonBillTrait;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //定时任务生成客户账单
        $customers=$this->getCustomers();
        if(count($customers)){
            foreach ($customers as $customer){
                //本月生成过则不再自动生成
                if($this->checkCustomerMonthBill($customer)==0){
                    //生成某个客户账单
                    $this->singleCustomerBillCreate($customer);
                }
            }
        }

    }

    //获取需要生成账单的客户
    public function getCustomers(){
        $today=date('j');
        $cooperate=[];
        //自然月非自然月账单:自然月账单3号生成
        if($today==3){
            $customers=CustomerManager::where('advance_order',1)
                ->orWhere(function(Builder $query) use ($today) {
                $query->where('advance_order', 2)
                    ->where('settle_date', $today);
            })
                ->get();
        }else{
            $customers=CustomerManager::where('advance_order',2)->where('settle_date',$today)->get();
        }
        if(count($customers)){
            foreach ($customers as $c){
                if($this->checkCustomer($c)){
                    $cooperate[]=$c;
                }
            }
        }
        return $cooperate;
    }
    //此客户是否需要生成账单
    public function checkCustomer($c){
        //停止合作后有账单生成
        if($c->cooperation_status==2){
            if(empty($c->breakup_time)){
                return false;
            }
            $billCount=FinanceCustomerBill::where('customer_id',$c->id)->where('created_at','>=',$c->breakup_time)->count('id');
            if($billCount>0){
                return false;
            }
        }
        //店铺为0
        $shopIds=$c->shopDetails()->pluck('id');
        if(count($shopIds)==0){
            return false;
        }
        //子账号数为0
        $count=SubAccount::whereIn('shop_id',$shopIds)->count('id');
        if($count==0){
            return false;
        }

        //所有店铺都停用：也许停用之前有部分帐要结
//        $breakupShopIds=$c->shopDetails()->where('cooperation_status',2)->pluck('id');
//        if(count($shopIds)==count($breakupShopIds)){
//            return false;
//        }
        //所有子账号都停用：也许停用之前有部分帐要结
//        $stopCount=SubAccount::whereIn('shop_id',$shopIds)->where('status',0)->count('id');
//        if($count==$stopCount){
//            return false;
//        }
        return true;
    }

    //获取账单周期
    public function getBillMonth($customer){
        $day = date('d');
        $lastMonth=date("m", strtotime(-$day.' day'));
        $year=date('Y');
        if($lastMonth==12){
            $year-=1;
        }
        if($customer->advance_order==1){
            return $year.'年'.$lastMonth.'月';
        }
        return $year.'年'.$lastMonth.'-'.date('m').'月';
    }
    //获取账单期
    public function getBillPeriod($customer,$type){
        $day = date('d');
        $lastMonth=date("Y/m/", strtotime(-$day.' day'));
        //自然月
        if($customer->advance_order==1){
            if($type=='start'){
                return $lastMonth.'01';
            }
            return date("Y/m/d", strtotime(-$day.' day'));
        }
        //非自然月
        $setDay=$customer->settle_date;
        if($type=='start'){
            if((int)$setDay<10){
                $setDay='0'.$setDay;
            }
            return $lastMonth.$setDay;
        }
        $billDay=date("Y/m/d");
        return date("Y/m/d",strtotime($billDay)-24*3600);
    }


}
